//模块就需要定义

define("register", ["jquery", "md5", "jquery.validate", "jquery.idcode"], function($) {

	return {
		init: function() {

			//使用验证码

			$.idcode.setCode(); //加载生成验证码方法

			$.validator.addMethod("checkUname", function(val, ele) {
				var reg = /^[a-zA-Z]+/;
				return reg.test(val);

			}, "用户名必须是字母开头");

			$uname = $("[name=uname]").val();
			//
			$("form").validate({
				//rules
				rules: {
					uname: {
						required: true,
						checkUname: true,
						rangelength: [6, 16],
						remote: {
							url: "./../server/userExist.php",
							type: "post",
							data: {
								"unameA": function() {
									return $("[name=uname]").val();
								}
							}
						}

					},
					upwd: {
						required: true,
						rangelength: [6, 20]
					},
					upwd1: {
						equalTo: "#upwd"
					},
					Txtidcode: {
						required: true,
					}
				},
				//messages
				messages: {
					uname: {
						required: "用户名必填",
						rangelength: "用户名必须是{0}到{1}之间",
						remote: "该用户名已经存在!"
					},
					upwd: {
						required: "密码必填",
						rangelength: "密码必须是{0}到{1}之间"
					},
					upwd1: {
						equalTo: "2次密码不一致"
					},
					Txtidcode: {
						required: "",
					}
				},
				//submitHandler
				submitHandler: function() {

					// if($("[name=ufile]")[0].files.length<=0){
					//     alert("请选择头像");
					//     return false;
					// }

					var IsBy = $.idcode.validateCode(); //调用返回值，返回值结果为true或者false
					if(IsBy) {

						var formdata = new FormData();
						var $dataArr = $("form").serializeArray();

						$dataArr.forEach((ele, index) => {
							// ele == {name: "uname", value: "admin11111"}

							if(ele.name != "Txtidcode" && ele.name != "upwd2") {

								if(ele.name == "upwd") {
									formdata.append(ele.name, $.md5(ele.value));
								} else {
									formdata.append(ele.name, ele.value);
								}
							}
						});
						// formdata.append("ufile", $("[name=ufile]")[0].files[0]);

						$.ajax({
							type: "post",
							url: "./../server/register.php",
							data: formdata,
							processData: false,
							contentType: false
						}).then(function(res) {
							console.log(res);
							confirm("注册成功是否现在登录") ? window.location = "login.html" : "";
						})

						return false;

					} else {
						alert("请重新输入")
					}

					return false;
				}
			})
		}
		//图片预览功能
		// preView : function(){
		//     $("[type=file]").on("change", function(){
		//         var read = new FileReader();
		//         read.readAsDataURL(this.files[0]);
		//         read.onload = function(ev){
		//             $("#head").attr("src", read.result);
		//         }
		//     })
		//
		// }
	}
})